package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.constant.ErrorConstantCode;
import cn.itsource.ymcc.domain.Course;
import cn.itsource.ymcc.domain.CourseChapter;
import cn.itsource.ymcc.mapper.CourseChapterMapper;
import cn.itsource.ymcc.service.ICourseChapterService;
import cn.itsource.ymcc.service.ICourseService;
import cn.itsource.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 课程章节 ， 一个课程，多个章节，一个章节，多个视频 服务实现类
 * </p>
 *
 * @author gwk
 * @since 2023-02-24
 */
@Service
public class CourseChapterServiceImpl extends ServiceImpl<CourseChapterMapper, CourseChapter> implements ICourseChapterService {

    @Autowired
    private ICourseService courseService;

    /**
     * 	业务流程，修改对应课程的章节数 +1
     * 	同时同步课程章节表，第几章
     * @param entity
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public boolean insert(CourseChapter entity) {
        //业务流程，修改对应课程的章节数 +1
        Long courseId = entity.getCourseId();
        Course course = courseService.selectById(courseId);
        AssertUtil.isNotNull(course, ErrorConstantCode.COURSE_ERROR_30010);

        //修改课程章节数
        Integer chapterCount = course.getChapterCount();
        if(chapterCount==null){
            chapterCount = 0;
        }
        course.setChapterCount(chapterCount+1);
        courseService.updateById(course);

        // 同时同步课程章节表，第几章
        entity.setNumber(chapterCount+1);

        return super.insert(entity);
    }

    /**
     * 根据课程id 查询章节集合
     * @param courseId
     * @return
     */
    @Override
    public List<CourseChapter> listByCourseId(Long courseId) {
        Wrapper<CourseChapter> wrapper = new EntityWrapper<>();
        wrapper.eq("course_id",courseId);
        List<CourseChapter> list = selectList(wrapper);
        return list;
    }
}
